
package com.vodafone.nowplus.android.peoplemail.singlesignon;

import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ResolveInfo;

/**
 * Class for sending an LOGIN_DETAILS_REQUEST together with a valid certificate
 */
public class SSOSender {

    private Activity callerActivity;

    public static final String certificateKeyName = "certificate";

    private CertificateReader certificateReader;

    public static final String LOGIN_DETAILS_REQUEST = "com.vodafone360.LOGIN_DETAILS_REQUEST";

    public static final int LOGIN_DETAILS_REQUEST_CODE = 0x0C042403;
    
    private boolean interrupted;
    
    /**
     * Sets the callerActivity and creates an instance of the CertificateReader
     * @param callerActivity Activity that sends out the intent.
     */
    public SSOSender(Activity callerActivity) {
        this.callerActivity = callerActivity;
        certificateReader = CertificateReader.getInstance(callerActivity);
    }

    /**
     * Sends out the LOGIN_DETAILS_REQUEST to all activities registered to handle such intents.
     * The intent contains an certificate signed with the CA certificate.
     */
    public boolean sendGetUserDataRequest() {
        Intent intent = new Intent(LOGIN_DETAILS_REQUEST, null);
        intent.putExtra(certificateKeyName, certificateReader.getCertificate());
        List<ResolveInfo> resolveInfos = callerActivity.getPackageManager().queryIntentActivities(
                intent, 0);
        if (resolveInfos != null) {
            String packageName;
            for (ResolveInfo resolveInfo : resolveInfos) {
                packageName = resolveInfo.activityInfo.applicationInfo.packageName;
                intent.setPackage(packageName);
                callerActivity.startActivityForResult(intent, LOGIN_DETAILS_REQUEST_CODE);
                if (interrupted) {
                    return true;
                }
            }
        }
        if (resolveInfos == null || resolveInfos.size() == 0) {
            return false;
        } else {
            return true;
        }

    }

    public void interrupt() {
        interrupted = true;
    }

}
